package me.malajis.equipmentprotect;

import org.bukkit.Sound;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.ClickType;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;

import java.util.Objects;

import static org.bukkit.enchantments.Enchantment.BINDING_CURSE;

public class ArmorListener implements Listener {
    @EventHandler
    public void onArmorByInventory(InventoryClickEvent event){
        if(Main.onEnable.getConfig().getBoolean("Config.ArmorListener")){
        ClickType clickType = event.getClick();
        //背包交互触发
        if(clickType.isLeftClick()){
            ItemStack itemStack = event.getCurrentItem();
            //检查是否有绑定诅咒
            if(itemStack!=null && itemStack.getEnchantmentLevel(BINDING_CURSE)>0){
                //将绑定诅咒删除
                removeBindingCurse(itemStack);
                //发送提示给玩家
                Player p = (Player) event.getWhoClicked();
                p.sendMessage(Objects.requireNonNull(Main.onEnable.getConfig().getString("Message.removetip")).replace("&", "§"));
                p.playSound(p.getLocation(), Sound.ENTITY_VILLAGER_YES, 1, 1);
            }
        }
    }
        }
    @EventHandler
    public void onArmorByHand(PlayerInteractEvent event) {
        if (Main.onEnable.getConfig().getBoolean("Config.ArmorListener")) {
            ItemStack itemStack = event.getItem();
            //检查是否有交互物品含有绑定诅咒
            if (itemStack != null && itemStack.getEnchantmentLevel(BINDING_CURSE) > 0) {
                //将绑定诅咒删除
                removeBindingCurse(itemStack);
                //发送提示给玩家
                Player p = event.getPlayer();
                p.sendMessage(Objects.requireNonNull(Main.onEnable.getConfig().getString("Message.removetip")).replace("&", "§"));
                p.playSound(p.getLocation(), Sound.ENTITY_VILLAGER_YES, 1, 1);
            }
        }
    }
    private void removeBindingCurse(ItemStack itemStack){
        ItemMeta itemMeta = itemStack.getItemMeta();
        if(itemMeta!=null){
            itemMeta.removeEnchant(BINDING_CURSE);
            itemStack.setItemMeta(itemMeta);
        }
    }
}
